﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace Asteroids.Game
{
    public class Highscores : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private int _score;
        public int Score
        {
            get { return _score; }
            private set
            {
                _score = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Score"));
                Console.WriteLine(Score);
            }
        }
        private XDocument XDoc { get; set; }

        private Highscores()
        {
            try
            {
                XDoc = XDocument.Load(Path.GetDirectoryName(Application.ExecutablePath) + "/Highscores.xml"); 
            }
            catch(FileNotFoundException){}
            OnPlayerScoreChanged(null, EventArgs.Empty);
            Game.Instance.OnCurrentScoreChanged += OnPlayerScoreChanged;
        }

        public void OnPlayerScoreChanged(object sender, EventArgs args)
        {
            Score = Game.Instance.Player.Score;
        }

        public void SaveScore(string name)
        {
            XDoc.Element("highscores").Add(new XElement("highscore", new XAttribute("name", name.ToUpper()),
                                                        new XAttribute("score", Score.ToString("D10"))));
            XDoc.Save(Path.GetDirectoryName(Application.ExecutablePath) + "/Highscores.xml");
            MainWindow.Instance.HighscoresUC.RefreshGrid();
        }

        private static Highscores _instance;
        public static Highscores Instance
        {
            get { return _instance ?? (_instance = new Highscores()); }
        }
    }

    public class HighscoresFORXAML
    {
        public Highscores Instance { get { return Highscores.Instance; } }
    }
}
